package com.example.skinhelper;

import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;


import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Time: 2020/9/23 0023
 * Author: zoulong
 */
public class SkinLayoutFactory implements LayoutInflater.Factory2 {
    private WeakReference<Activity> targetActivity;


    public SkinLayoutFactory(Activity targetActivity) {
        this.targetActivity = new WeakReference<>(targetActivity);
    }

    @Nullable
    @Override
    public View onCreateView(@Nullable View parent, @NonNull String name, @NonNull Context context, @NonNull AttributeSet attrs) {
        View view = ViewProducer.createViewFromTag(context, name, attrs);

        if (view == null) return null;
        SkinView skinView = new SkinView();
        skinView.setTargetView(view);
        Map<String, String> stringMap = new HashMap<>();
        for (int i = 0; i < attrs.getAttributeCount(); i++) {
            String attributeName = attrs.getAttributeName(i);
            List<ViewSetting> machViewSettings = SkinIns.getInstance().getViewSettings(attributeName);
            if (machViewSettings.size() == 0) {
                continue;
            }

//            Log.d("SkinLayoutFactory", "onCreateView: parent=" + parent + "  view=" + view);
//            Log.d("SkinLayoutFactory", "onCreateView:  attributeName=" + attributeName + "  getAttributeValue=" + attrs.getAttributeValue(i));
            stringMap.put(attributeName, attrs.getAttributeValue(i));
        }
        if (stringMap.size()>0) {
            skinView.setAttrNV(stringMap);
            SkinIns.getInstance().getSkinViewManager().addSkinView(targetActivity.get(), skinView);
            SkinIns.getInstance().getSkinViewManager().onStartSkinView(skinView);
        }
        return view;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull String name, @NonNull Context context, @NonNull AttributeSet attrs) {
        Log.d("SkinLayoutFactory", "onCreateView: 3 p");
        return null;
    }
}
